﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    ViewData["Title"] = "生产派单管理";
    Layout = null;
}

@Html.AntiForgeryToken()

<!-- 先加载CSS -->
<link href="https://cdn.bootcdn.net/ajax/libs/layui/2.6.8/css/layui.min.css" rel="stylesheet">

<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-header">
            <h3>生产派单管理</h3>
        </div>
        <div class="layui-card-body">
            <form class="layui-form" id="searchForm" lay-filter="searchForm">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">任务名称</label>
                        <div class="layui-input-inline">
                            <input type="text" name="taskName" placeholder="请输入任务名称" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">工单编号</label>
                        <div class="layui-input-inline">
                            <input type="text" name="productionOrderCode" placeholder="请输入工单编号" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">工序名称</label>
                        <div class="layui-input-inline">
                            <input type="text" name="processesName" placeholder="请输入工序名称" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <button type="submit" class="layui-btn" lay-submit lay-filter="searchForm">
                            <i class="layui-icon layui-icon-search"></i> 查询
                        </button>
                        <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                    </div>
                </div>
            </form>
            <div style="margin-bottom: 10px;">
                <div class="layui-btn-group">
                    <button class="layui-btn layui-btn-normal" id="addBtn">
                        <i class="layui-icon layui-icon-add-1"></i> 添加
                    </button>
                    <button class="layui-btn layui-btn-danger" id="batchDeleteBtn">
                        <i class="layui-icon layui-icon-delete"></i> 批量删除
                    </button>
                    <button class="layui-btn layui-btn-warm" id="batchEditBtn">
                        <i class="layui-icon layui-icon-edit"></i> 批量修改
                    </button>
                </div>
            </div>
            <table id="orderDispatchTable" lay-filter="orderDispatchTable"></table>
        </div>
    </div>
</div>

<!-- 添加弹窗表单模板 -->
<script type="text/html" id="formTpl">
    <form class="layui-form" lay-filter="mainForm" style="margin: 20px;">
        <input type="hidden" name="Id">
        <div class="layui-form-item">
            <label class="layui-form-label required">生产工单编号</label>
            <div class="layui-input-inline" style="width: 250px;">
                <input type="text" name="ProductionOrderCode" required lay-verify="required" placeholder="请输入生产工单编号" autocomplete="off" class="layui-input">
            </div>
            <input type="checkbox" lay-skin="switch" lay-filter="autoGenOrderCodeSwitch" lay-text="自动生成|手动输入" id="autoGenOrderCodeSwitch" checked>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label required">任务名称</label>
            <div class="layui-input-block">
                <input type="text" name="TaskName" required lay-verify="required" placeholder="请输入任务名称" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">工作站名称</label>
            <div class="layui-input-block">
                <input type="text" name="WorkstationName" placeholder="请输入工作站名称" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label required">工序名称</label>
            <div class="layui-input-block">
                <input type="text" name="ProcessesName" required lay-verify="required" placeholder="请输入工序名称" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">产品名称</label>
            <div class="layui-input-block">
                <input type="text" name="ProductionName" placeholder="请输入产品名称" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label required">开始生产时间</label>
            <div class="layui-input-block">
                <input type="text" name="StartTime" id="startTime" required lay-verify="required" placeholder="请选择开始生产时间" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label required">完成生产时间</label>
            <div class="layui-input-block">
                <input type="text" name="EndTime" id="endTime" required lay-verify="required" placeholder="请选择完成生产时间" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">派单对象</label>
            <div class="layui-input-inline">
                <input type="text" name="DispatchName" id="dispatchNameInput" placeholder="请选择派单对象" readonly class="layui-input" style="cursor:pointer;">
            </div>
           
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">用户</label>
            <div class="layui-input-block">
                <select name="UserId" id="userIdSelect" lay-search required lay-verify="required">
                    <option value="">请选择用户</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="submitForm">提交</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </div>
    </form>
</script>

<script type="text/html" id="userTableTpl">
    <form class="layui-form" id="userSearchForm" style="margin:10px; display: flex; gap: 20px; align-items: center;">
        <div>
            <label style="display:inline-block; width:70px;">用户名</label>
            <input type="text" name="userName" placeholder="请输入用户名" autocomplete="off" class="layui-input" style="width:200px; display:inline-block;">
        </div>
        <div>
            <label style="display:inline-block; width:70px;">昵称</label>
            <input type="text" name="userNickName" placeholder="请输入昵称" autocomplete="off" class="layui-input" style="width:200px; display:inline-block;">
        </div>
        <button class="layui-btn layui-btn-sm" lay-submit lay-filter="userSearch">查询</button>
    </form>
    <table id="userTable" lay-filter="userTable"></table>
</script>

<!-- 先加载jQuery，再加载Layui -->
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/layui/2.6.8/layui.min.js"></script>

<script>
    var tableIns; // 声明为全局变量
    layui.use(['table', 'form', 'layer', 'laydate'], function(){
        var table = layui.table;
        var form = layui.form;
        var layer = layui.layer;
        var laydate = layui.laydate;
        var $ = layui.$;

        // 渲染表格
        tableIns = table.render({
            elem: '#orderDispatchTable',
            url: '/OrderDispatch/GetOrderDispatchList',
            method: 'get',
            where: {},
            page: true,
            limit: 10,
            limits: [10, 20, 50, 100],
            cols: [[
                { type: 'checkbox', fixed: 'left' },
                {field: 'productionOrderCode', title: '生产工单编号', minWidth: 120},
                {field: 'taskName', title: '任务名称', minWidth: 120},
                {field: 'workstationName', title: '工作站名称', minWidth: 120},
                {field: 'processesName', title: '工序名称', minWidth: 120},
                {field: 'productionName', title: '产品名称', minWidth: 120},
                {field: 'startTime', title: '开始生产时间', minWidth: 160, templet: function(d){ return d.startTime ? d.startTime.replace('T', ' ').substring(0, 19) : ''; }},
                {field: 'endTime', title: '完成生产时间', minWidth: 160, templet: function(d){ return d.endTime ? d.endTime.replace('T', ' ').substring(0, 19) : ''; }},
                {field: 'dispatchName', title: '派单对象', minWidth: 120},
                {field: 'userNickName', title: '用户', minWidth: 120},
                {fixed: 'right', title: '操作', toolbar: '#tableBar', width: 150}
            ]],
            response: {
                statusCode: 0
            },
            parseData: function(res) {
                return {
                    "code": res.code,
                    "msg": res.msg,
                    "count": res.count || res.TotalCount,
                    "data": res.data || res.items
                };
            }
        });

        // 查询
        form.on('submit(searchForm)', function(data){
            tableIns.reload({
                where: data.field,
                page: { curr: 1 }
            });
            return false;
        });

        // 添加按钮
        $('#addBtn').on('click', function(){
            layer.open({
                type: 1,
                title: '添加生产派单',
                area: ['600px', '600px'],
                content: $('#formTpl').html(),
                success: function(layero, index){
                    form.render(null, 'mainForm');
                    // 默认自动生成编号并只读
                    $.get('/OrderDispatch/GenerateProductionOrderCode', function(res) {
                        if(res.code === 0 && res.productionOrderCode){
                            layero.find('input[name="ProductionOrderCode"]').val(res.productionOrderCode).prop('readonly', true);
                        }
                    });
                    // 监听开关切换
                    form.on('switch(autoGenOrderCodeSwitch)', function(data){
                        if(data.elem.checked){
                            // 自动生成
                            $.get('/OrderDispatch/GenerateProductionOrderCode', function(res) {
                                if(res.code === 0 && res.productionOrderCode){
                                    layero.find('input[name="ProductionOrderCode"]').val(res.productionOrderCode).prop('readonly', true);
                                }
                            });
                        }else{
                            // 手动输入
                            layero.find('input[name="ProductionOrderCode"]').val('').prop('readonly', false);
                        }
                    });
                    // 渲染日期选择器
                    laydate.render({
                        elem: '#startTime',
                        type: 'datetime'
                    });
                    laydate.render({
                        elem: '#endTime',
                        type: 'datetime'
                    });
                    // 动态加载用户下拉
                    $.get('/OrderDispatch/ShowUser', { pageIndex: 1, pageSize: 1000 }, function(res){
                        if(res.code === 0 && res.data && res.data.length > 0){
                            var options = '<option value="">请选择用户</option>';
                            res.data.forEach(function(user){
                                options += '<option value="' + user.id + '">' + (user.userNickName || user.userName) + '</option>';
                            });
                            layero.find('select[name="UserId"]').html(options);
                            form.render('select', 'mainForm');
                        }
                    });
                    // 监听派单对象输入框点击，弹出用户表格
                    layero.find('#dispatchNameInput').on('click', function() {
                        layer.open({
                            type: 1,
                            title: '选择派单对象',
                            area: ['500px', '400px'],
                            content: $('#userTableTpl').html(),
                            success: function(userLayero, userIndex) {
                                // 渲染用户表格
                                var userTableIns = table.render({
                                    elem: userLayero.find('#userTable'),
                                    url: '/OrderDispatch/ShowUser',
                                    method: 'get',
                                    page: true,
                                    limit: 10,
                                    cols: [[
                                        {field: 'userName', title: '用户名', minWidth: 120},
                                        {field: 'userNickName', title: '昵称', minWidth: 120},
                                        {title: '操作', align: 'center', templet: function(d){
                                            return '<button class="layui-btn layui-btn-xs select-user-btn" data-name="'+(d.userNickName||d.userName)+'">选择</button>';
                                        }}
                                    ]],
                                    response: { statusCode: 0 },
                                    parseData: function(res) {
                                        return {
                                            "code": res.code,
                                            "msg": res.msg,
                                            "count": res.count || res.TotalCount,
                                            "data": res.data || res.items
                                        };
                                    }
                                });
                                // 监听表格内选择按钮
                                userLayero.on('click', '.select-user-btn', function() {
                                    var name = $(this).data('name');
                                    // 填充到主表单input
                                    layero.find('input[name="DispatchName"]').val(name);
                                    layer.close(userIndex);
                                });
                                // 绑定查询事件，确保在弹窗内生效
                                layui.form.on('submit(userSearch)', function(data){
                                    userTableIns.reload({
                                        where: data.field,
                                        page: { curr: 1 }
                                    });
                                    return false;
                                });
                                layui.form.render(null, userLayero.find('#userSearchForm'));
                            }
                        });
                    });
                    form.on('submit(submitForm)', function(formData){
                        var url = data ? '/OrderDispatch/Update' : '/OrderDispatch/AddOrderDispatch';
                        var token = $('input[name="__RequestVerificationToken"]').val();
                        var ajaxOptions = {
                            url: url,
                            type: 'POST',
                            success: function(res){
                                if(res.code === 0){
                                    layer.msg(data ? '修改成功' : '添加成功');
                                    layer.close(index);
                                    tableIns.reload();
                                } else {
                                    layer.msg(res.msg || (data ? '修改失败' : '添加失败'));
                                }
                            },
                            error: function(){
                                layer.msg('服务器错误');
                            }
                        };
                        if(data){ // 编辑
                            var postData = formData.field;
                            postData.__RequestVerificationToken = token;
                            ajaxOptions.data = postData;
                        }else{ // 新增
                            var postData = formData.field;
                            postData.__RequestVerificationToken = token;
                            ajaxOptions.data = postData;
                        }
                        $.ajax(ajaxOptions);
                        return false;
                    });
                }
            });
        });

        // 批量删除
        $('#batchDeleteBtn').on('click', function(){
            var checkStatus = table.checkStatus('orderDispatchTable');
            var data = checkStatus.data;
            if(data.length === 0){
                layer.msg('请选择要删除的记录');
                return;
            }
            layer.confirm('确定要删除选中的'+data.length+'条记录吗？', function(index){
                var ids = data.map(function(item){ return item.id; });
                $.ajax({
                    url: '/OrderDispatch/BatchDelete',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(ids),
                    headers: {
                        'RequestVerificationToken': $('input[name="__RequestVerificationToken"]').val()
                    },
                    success: function(res){
                        if(res.code === 0){
                            layer.msg(res.msg);
                            tableIns.reload();
                        } else {
                            layer.msg(res.msg);
                        }
                    },
                    error: function(xhr){
                        layer.msg(xhr.responseJSON?.msg || '操作失败，请重试');
                    }
                });
                layer.close(index);
            });
        });

        // 批量修改
        $('#batchEditBtn').on('click', function(){
            var checkStatus = table.checkStatus('orderDispatchTable');
            var data = checkStatus.data;
            if(data.length === 0){
                layer.msg('请选择要修改的记录');
                return;
            }
            var index = 0;
            function editNext() {
                if(index >= data.length) return;
                openForm(data[index], function(){
                    index++;
                    editNext();
                });
            }
            editNext();
        });

        // 监听工具条
        // 单个编辑和删除
        table.on('tool(orderDispatchTable)', function(obj){
            var data = obj.data;
            if(obj.event === 'edit'){
                openForm(data);
            } else if(obj.event === 'del'){
                layer.confirm('确定要删除此记录吗？', function(index){
                    $.ajax({
                        url: '/OrderDispatch/Delete',
                        type: 'POST',
                        data: { id: data.id },
                        headers: {
                            'RequestVerificationToken': $('input[name="__RequestVerificationToken"]').val()
                        },
                        success: function(res){
                            if(res.code === 0){
                                obj.del();
                                layer.msg('删除成功');
                                tableIns.reload();
                            } else {
                                layer.msg(res.msg || '删除失败');
                            }
                        },
                        error: function(xhr){
                            layer.msg(xhr.responseJSON?.msg || '删除失败，请重试');
                        }
                    });
                    layer.close(index);
                });
            }
        });

        form.render();
    });

    function openForm(data, callback) {
        layer.open({
            type: 1,
            title: data ? '编辑生产派单' : '添加生产派单',
            area: ['600px', '600px'],
            content: $('#formTpl').html(),
            success: function(layero, index){
                var form = layui.form;
                var laydate = layui.laydate;
                form.render(null, 'mainForm');
                // 如果是编辑，回填数据
                if(data){
                    form.val('mainForm', {
                        "Id": data.id,
                        "ProductionOrderCode": data.productionOrderCode,
                        "TaskName": data.taskName,
                        "WorkstationName": data.workstationName,
                        "ProcessesName": data.processesName,
                        "ProductionName": data.productionName,
                        "StartTime": data.startTime ? data.startTime.replace('T', ' ').substring(0, 19) : '',
                        "EndTime": data.endTime ? data.endTime.replace('T', ' ').substring(0, 19) : '',
                        "DispatchName": data.dispatchName,
                        "UserId": data.userId
                    });
                }
                // 渲染日期选择器
                laydate.render({ elem: '#startTime', type: 'datetime' });
                laydate.render({ elem: '#endTime', type: 'datetime' });

                // 动态加载用户下拉
                $.get('/OrderDispatch/ShowUser', { pageIndex: 1, pageSize: 1000 }, function(res){
                    if(res.code === 0 && res.data && res.data.length > 0){
                        var options = '<option value="">请选择用户</option>';
                        res.data.forEach(function(user){
                            options += '<option value="' + user.id + '">' + (user.userNickName || user.userName) + '</option>';
                        });
                        layero.find('select[name="UserId"]').html(options);
                        form.render('select', 'mainForm');
                        // 回填用户
                        if(data && data.userId){
                            layero.find('select[name="UserId"]').val(data.userId);
                            form.render('select', 'mainForm');
                        }
                    }
                });

                // 自动生成编号开关逻辑
                var switchElem = layero.find('#autoGenOrderCodeSwitch')[0];
                if(switchElem && switchElem.checked){
                    layero.find('input[name="ProductionOrderCode"]').prop('readonly', true);
                } else {
                    layero.find('input[name="ProductionOrderCode"]').prop('readonly', false);
                }
                form.on('switch(autoGenOrderCodeSwitch)', function(dataSwitch){
                    if(dataSwitch.elem.checked){
                        $.get('/OrderDispatch/GenerateProductionOrderCode', function(res) {
                            if(res.code === 0 && res.productionOrderCode){
                                layero.find('input[name="ProductionOrderCode"]').val(res.productionOrderCode).prop('readonly', true);
                            }
                        });
                    }else{
                        layero.find('input[name="ProductionOrderCode"]').val('').prop('readonly', false);
                    }
                });

                // 事件绑定：派单对象输入框点击弹窗
                layero.find('#dispatchNameInput').on('click', function() {
                    layer.open({
                        type: 1,
                        title: '选择派单对象',
                        area: ['500px', '400px'],
                        content: $('#userTableTpl').html(),
                        success: function(userLayero, userIndex) {
                            var table = layui.table;
                            // 渲染用户表格
                            var userTableIns = table.render({
                                elem: userLayero.find('#userTable'),
                                url: '/OrderDispatch/ShowUser',
                                method: 'get',
                                page: true,
                                limit: 10,
                                cols: [[
                                    {field: 'userName', title: '用户名', minWidth: 120},
                                    {field: 'userNickName', title: '昵称', minWidth: 120},
                                    {title: '操作', align: 'center', templet: function(d){
                                        return '<button class="layui-btn layui-btn-xs select-user-btn" data-name="'+(d.userNickName||d.userName)+'">选择</button>';
                                    }}
                                ]],
                                response: { statusCode: 0 },
                                parseData: function(res) {
                                    return {
                                        "code": res.code,
                                        "msg": res.msg,
                                        "count": res.count || res.TotalCount,
                                        "data": res.data || res.items
                                    };
                                }
                            });
                            // 监听表格内选择按钮
                            userLayero.on('click', '.select-user-btn', function() {
                                var name = $(this).data('name');
                                // 填充到主表单input
                                layero.find('input[name="DispatchName"]').val(name);
                                layer.close(userIndex);
                            });
                            // 绑定查询事件，确保在弹窗内生效
                            layui.form.on('submit(userSearch)', function(data){
                                userTableIns.reload({
                                    where: data.field,
                                    page: { curr: 1 }
                                });
                                return false;
                            });
                            layui.form.render(null, userLayero.find('#userSearchForm'));
                        }
                    });
                });

                // 提交
                form.on('submit(submitForm)', function(formData){
                    var url = data ? '/OrderDispatch/Update' : '/OrderDispatch/AddOrderDispatch';
                    var token = $('input[name="__RequestVerificationToken"]').val();
                    var ajaxOptions = {
                        url: url,
                        type: 'POST',
                        success: function(res){
                            if(res.code === 0){
                                layer.msg(data ? '修改成功' : '添加成功');
                                layer.close(index);
                                tableIns.reload();
                                if(callback) callback(); // 关闭后继续下一个
                            } else {
                                layer.msg(res.msg || (data ? '修改失败' : '添加失败'));
                            }
                        },
                        error: function(){
                            layer.msg('服务器错误');
                        }
                    };
                    if(data){ // 编辑
                        var postData = formData.field;
                        postData.__RequestVerificationToken = token;
                        ajaxOptions.data = postData;
                    }else{ // 新增
                        var postData = formData.field;
                        postData.__RequestVerificationToken = token;
                        ajaxOptions.data = postData;
                    }
                    $.ajax(ajaxOptions);
                    return false;
                });
            }
        });
    }
</script>

<style>

    .layui-tree-txt {
        color: #333;
        font-size: 14px;
    }

    /* 卡片样式 */
    .layui-card {
        margin-bottom: 15px;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
    }

    .layui-card-header {
        font-weight: bold;
        background-color: #f8f8f8;
    }

    /* 容器样式 */
    .layui-container {
        padding: 15px;
    }

    /* 表格工具栏 */
    .layui-table-tool {
        background-color: #f8f8f8;
    }
</style>

<!-- 工具条模板 -->
<script type="text/html" id="tableBar">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
